package cn.cdiothree.controller;


import cn.cdiothree.domain.Result;
import cn.cdiothree.domain.auth.ResponseUserToken;
import cn.cdiothree.domain.auth.Role;
import cn.cdiothree.domain.auth.User;
import cn.cdiothree.domain.auth.UserDetail;
import cn.cdiothree.enums.MessageEnum;
import cn.cdiothree.exception.UserException;
import cn.cdiothree.service.AuthService;
import cn.cdiothree.service.UserService;
import cn.cdiothree.service.impl.RegisterServiceImpl;
import cn.cdiothree.util.ResultUtil;
import cn.cdiothree.vo.ResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * 用户控制层
 * @author cumthing
 */
@RestController
@Api(tags = "登陆注册及刷新token")
@RequestMapping("/api/v1")
@Slf4j
public class AuthController {
    @Value("${jwt.header}")
    private String tokenHeader;

    private final AuthService authService;

    @Autowired
    public AuthController(AuthService authService) {
        this.authService = authService;
    }
    @Autowired
    private RegisterServiceImpl registerService;
    @Autowired
    private UserService userService;


    /**
     * 用户登录
     * @param user
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/login")
    @ApiOperation(value = "登陆", notes = "登陆成功返回token,登陆之前请先注册账号")
    public Result<ResponseUserToken> login(
            @Valid @RequestBody User user, HttpServletRequest request,HttpServletResponse response){
        String remFlag = request.getParameter("remFlag");
        String a  = "1";
        if (a.equals(remFlag)){
            String loginInfo = user.getName()+","+user.getPassword();
            Cookie userCookie = new Cookie("loginInfo",loginInfo);
            //存活期为关闭浏览器cookie消失
            userCookie.setMaxAge(-1);
            userCookie.setPath("/");
            response.addCookie(userCookie);
            final ResponseUserToken response1 = authService.login(user.getName(), user.getPassword());
            return ResultUtil.success(response1);
        }
        final ResponseUserToken response1 = authService.login(user.getName(), user.getPassword());
        return ResultUtil.success(response1);
    }

    /**
     * 用户登出
     * @param request
     * @return
     */
    @GetMapping(value = "/logout")
    @ApiOperation(value = "登出", notes = "退出登陆")
    @ApiImplicitParams({@ApiImplicitParam(name = "Authorization", value = "Authorization token", required = true, dataType = "string", paramType = "header")})
    public Result logout(HttpServletRequest request){
        String token = request.getHeader(tokenHeader);
        if (token == null) {
            throw new UserException(MessageEnum.UNAUTHORIZED);
        }
        authService.logout(token);
        return ResultUtil.success();
    }

    /**
     * 根据token获取用户信息
     * @param request
     * @return
     */
    @GetMapping(value = "/user")
    @ApiOperation(value = "根据token获取用户信息", notes = "根据token获取用户信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "Authorization", value = "Authorization token", required = true, dataType = "string", paramType = "header")})
    public Result getUser(HttpServletRequest request){
        String token = request.getHeader(tokenHeader);
        if (token == null) {
            throw new UserException(MessageEnum.UNAUTHORIZED);
        }
        UserDetail userDetail = authService.getUserByToken(token);
        return ResultUtil.success(userDetail);
    }


    @PostMapping(value = "/sign")
    @ApiOperation(value = "用户注册")
    public Result sign(@RequestBody User user ) {
        if (StringUtils.isAnyBlank(user.getName(), user.getPassword())) {
            throw new UserException(MessageEnum.BAD_REQUEST);
        }
        UserDetail userDetail = new UserDetail(user.getName(), user.getPassword(),user.getTelephone(),Role.builder().id(1L).build());
        return ResultUtil.success(authService.register(userDetail));
    }

    /**
     * 获取验证码
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/verify")
    public ResponseEntity<?> verify(HttpServletRequest request, HttpServletResponse response){
        registerService.verify(request,response);
        return ResponseEntity.status(HttpStatus.OK).body(null);
    }

    /**
     * 用户注册
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/register")
    public ResponseEntity<?> register(HttpServletRequest request, HttpServletResponse response) {
        registerService.register(request, response);
        return ResponseEntity.status(HttpStatus.OK).body("恭喜你已经成功注册");
    }

    /**
     * 用户修改密码
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/change-secret")
    public ResponseEntity<?> changeSecret(HttpServletRequest request, HttpServletResponse response) {
        String token = request.getHeader(tokenHeader);
        if (token == null) {
            throw new UserException(MessageEnum.UNAUTHORIZED);
        }
        registerService.changeSecret(request, response,token);
        return ResponseEntity.status(HttpStatus.OK).body("恭喜你密码修改成功");
    }

    /**
     * 用户忘记密码，找回密码
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/forget-secret")
    public ResponseEntity<?> forgetSecret(HttpServletRequest request, HttpServletResponse response) {
        registerService.forgetSecret(request, response);
        return ResponseEntity.status(HttpStatus.OK).body("恭喜你密码修改成功");
    }

    /**
     * 统计在线人数
     * @param gap
     * @return
     */
    @GetMapping("/online")
    public ResultVo online(@RequestParam(value = "gap", required = false, defaultValue = "600000")  Integer gap) {
        log.info("进行用户统计");
        return userService.onlineUser(gap.longValue());
    }

}
